package com.gzsxy.sso.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.gzsxy.sso.core.model.SessionUser;
import com.gzsxy.sso.core.utils.SessionUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充
 */
@Component
@Slf4j
public class CommonMetaObjectHandler implements MetaObjectHandler {


    //添加
    @Override
    public void insertFill(MetaObject metaObject) {
            SessionUser sessionUser = SessionUserUtil.getSessionUser();
            this.setFieldValByName("createTime", new Date(), metaObject); //update_time实体类当中的属性
            this.setFieldValByName("updateTime", new Date(), metaObject);
            if (!ObjectUtils.isEmpty(sessionUser)){
                this.setFieldValByName("addUser",sessionUser.getUserName(),metaObject);
                this.setFieldValByName("updateUser",sessionUser.getUserName(),metaObject);
            }
    }

    //更新
    @Override
    public void updateFill(MetaObject metaObject) {
            SessionUser sessionUser = SessionUserUtil.getSessionUser();
            this.setFieldValByName("updateTime", new Date(), metaObject);
            if (!ObjectUtils.isEmpty(sessionUser)){
                this.setFieldValByName("updateUser",sessionUser.getUserName(),metaObject);
            }
    }
}